package org.hshk.message.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.hshk.message.BaseController;
import org.hshk.message.entity.CpMsgMember;
import org.hshk.message.mq.MQProducer;
import org.hshk.message.repository.CpMsgMemberRepository;
import org.hshk.message.service.CpMsgMemberSignService;
import org.hshk.message.utils.MobileMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created With IntelliJ IDEA
 * User: WangYong
 * User: WangYong
 * Date: 2017/2/24 0024
 * Time: 09:35
 * ProjectName: msgCenterAPI
 * 短信发送类
 */
@Api(value = "短信发送 API")
@RestController

@RequestMapping("/messages")
public class MsgSendController extends BaseController {

    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(MsgSendController.class);
    @Autowired
    private CpMsgMemberSignService cpMsgMemberSignService;
    @Autowired
    private MQProducer mqProducer;
    @Autowired
    CpMsgMemberRepository cpMsgMemberRepository;
    //线程对象暂存
    private ThreadLocal<Gson> local = new ThreadLocal<Gson>();

    //对象存放类
    private Gson getGson() {
        if (null == local.get()) {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }

    /**
     * 2017年2月27日 09:35:22
     * 短信发送
     *
     * @param brandId
     * @param mobile
     * @param templateCode
     * @param parameters
     * @return
     */
    @ApiOperation(value = "短信发送")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "brandId", value = "品牌id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "templateCode", value = "模板编号", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "parameters", value = "变量参数", required = true, dataType = "string", paramType = "path")
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")
    })
    @ResponseBody
    @RequestMapping(value = "/brandId/{brandId}/mobile/{mobile}/templateCode/{templateCode}/parameters/{parameters:.+}", method = RequestMethod.POST, produces = "application/json")
    public String sendPost(@PathVariable int brandId, @PathVariable String mobile,
                           @PathVariable String templateCode, @PathVariable String[] parameters) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            log.info("MsgSendController.sendPost [ brandId=" + brandId + ", templateCode=" + templateCode +
                    ", mobile=" + mobile + ", parameters=" + Arrays.toString(parameters) + " ]");
            Map<String, Object> paramMsg = new HashMap<String, Object>();
            //首先，检测参数
            if (0 == brandId) {
                paramMsg.put("brandId", "参数错误.");
            }
            if (null == mobile || "".equals(mobile)) {
                paramMsg.put("mobile", "参数错误.");
            }
            if (!MobileMatcher.match(mobile)) {
                paramMsg.put("mobile", "参数格式错误.");
            }
            if (null == templateCode || "".equals(templateCode)) {
                paramMsg.put("templateCode", "参数错误.");
            }
            if (null == parameters || 0 == parameters.length) {
                paramMsg.put("parameters", "参数错误.");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }
            //根据id,查询商户充值信息
            List<CpMsgMember> cpMsgMembers = cpMsgMemberRepository.findByBrandId(brandId);
            if (null == cpMsgMembers || cpMsgMembers.size() <= 0) {
                resultMap.put("resultCode", "fail");
                resultMap.put("resultMsg", "未开通短信服务");
                return getGson().toJson(resultMap);
            }
            if (cpMsgMembers.get(0).getBalanceCount() <= 0) {
                resultMap.put("resultCode", "fail");
                resultMap.put("resultMsg", "余额不足，请及时充值");
                return getGson().toJson(resultMap);
            }
            JSONObject json = new JSONObject();
            json.put("brandId", brandId);
            json.put("mobile", mobile);
            json.put("templateCode", templateCode);
            json.put("parameters", parameters);
            //将消息放入队列，等待被消费
            mqProducer.sendMessage(json);
            resultMap.put("resultCode", "success");
            resultMap.put("resultMsg", "成功");
            return getGson().toJson(resultMap);
        } catch (Exception ex) {
            //出现异常时
            log.error("MsgSendController.sendPost " + ex.getMessage());
            ex.printStackTrace();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }


}
